//
//  NetWorkHelper.m
//  HuaRun2
//
//  Created by admin on 17/8/30.
//  Copyright © 2017年 Sunny. All rights reserved.
//

#import "NetWorkHelper.h"
#import "AFNetworking.h"
#import "UserModel.h"
#import "XHNHudManager.h"

@implementation NetWorkHelper

+ (NetWorkHelper *)shareNetWorkHelper {
    static NetWorkHelper * helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[NetWorkHelper alloc] init];
    });
    return helper;
}

+ (void)cancelAllRequest {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.operationQueue cancelAllOperations];
}

+ (void)getWithURLString:(NSString *)urlString
              parameters:(id)parameters
                 success:(SuccessBlock)successBlock
                 failure:(FailureBlock)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /***  可以接受的类型*/
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    /***  请求超时的时间*/
////    manager.requestSerializer.timeoutInterval = 3;
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", nil];
    UserModel * userModel = [UserModel getCurrentUserModel];

    //每个参数上添加一个 access_token参数
    NSMutableDictionary * finalDic = [NSMutableDictionary dictionaryWithDictionary:parameters];
    [finalDic setValue:userModel.access_token forKey:@"access_token"];
    
    [manager GET:urlString parameters:finalDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        
        if (successBlock) {
            NSLog(@"\n%@ %@ \n -------------\n %@\n msg = %@\n", urlString, finalDic, responseObject, responseObject[@"msg"]);
            if ([responseObject[@"code"] isEqual: kTokenInVaild]) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationShowLoginVC object:responseObject[@"msg"] ? responseObject[@"msg"] : @""];
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefrshToken object:nil];

                return;
            }
            successBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            NSLog(@"网络异常 - T_T%@\n%@\n %@", urlString, finalDic, error);
            failureBlock(error);
        }
        
    }];
}

+ (void)postWithURLString:(NSString *)urlString
               parameters:(id)parameters
                  success:(SuccessBlock)successBlock
                  failure:(FailureBlock)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer.timeoutInterval = 3;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", nil];
//每个URL 后面拼接一个 access_token参数
//    access_token=12345
    
    NSString * finalUrlString ;
    //如果不是登陆接口，需要在URL 后面拼接上access_token
    NSArray * urls = [urlString componentsSeparatedByString:@"/"];
    if (urls.count > 0) {
        NSString *tempUrl = [urls lastObject];
        if ([tempUrl isEqualToString:@"loginFromApp"]) {
            NSLog(@"是登陆接口");
            finalUrlString = urlString;
        }else {
            UserModel * userModel = [UserModel getCurrentUserModel];
            finalUrlString = [urlString stringByAppendingFormat:@"?access_token=%@",
             userModel.access_token];
        }
    }

    [manager POST:finalUrlString parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (successBlock) {
            
            NSLog(@"\n%@ %@ \n -------------\n %@\n msg = %@\n", finalUrlString, parameters, responseObject, responseObject[@"msg"]);
                        
            if ([responseObject[@"code"] isEqual:kTokenInVaild]) {

                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationShowLoginVC object:responseObject[@"msg"] ? responseObject[@"msg"] : @""];
                
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefrshToken object:nil];

//                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefrshToken object:responseObject[@"msg"] ? responseObject[@"msg"] : @""];

                return;
            }
            successBlock(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            NSLog(@"网络异常 - T_T%@\n%@\n %@", finalUrlString, parameters, error);

            failureBlock(error);
        }
        
    }];
    
}
+ (void)uploadImageWithPath:(NSString *)path
                      image:(UIImage *)image
                     params:(NSDictionary *)params
                    success:(SuccessBlock)successBlock
                    failure:(FailureBlock)failureBlock {
    NSArray *array = [NSArray arrayWithObject:image];
    [self uploadImageWithPath:path
                       photos:array
                       params:params
                        ocrId:nil
                      success:successBlock
                      failure:failureBlock];
    
}


+ (void)uploadImageWithPath:(NSString *)path
                     photos:(NSArray *)photos
                     params:(NSDictionary *)params
                      ocrId:(NSString *)ocrId
                    success:(SuccessBlock)successBlock
                    failure:(FailureBlock)failureBlock {

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

    NSString * ocrStr = ocrId ? [NSString stringWithFormat:@"&ocrId=%@", ocrId] : @"";
    UserModel * userModel = [UserModel getCurrentUserModel];
    NSString * finalUrlString = [path stringByAppendingFormat:@"?access_token=%@%@",
                                 userModel.access_token, ocrStr];
    [manager POST:finalUrlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < photos.count; i ++) {
            
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            
//            NSString *str=[formatter stringFromDate:[NSDate date]];
//            NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
            UIImage *image = photos[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
            [formData appendPartWithFileData:imageData
                                        name:/*[NSString stringWithFormat:@"upload%d",i+1]*/ @"file"
                                    fileName:@"file"/*fileName*/
                                    mimeType:@"image/jpeg"];
            
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if (successBlock) {
            NSLog(@"\n%@ %@ \n -------------\n %@\n msg = %@\n", path, params, responseObject, responseObject[@"msg"]);
            if ([responseObject[@"code"] isEqual: kTokenInVaild]) {
//                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRefrshToken object:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationShowLoginVC object:responseObject[@"msg"] ? responseObject[@"msg"] : @""];

                return;
            }
            successBlock(responseObject);
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failureBlock) {
            failureBlock(error);
            NSLog(@"网络异常 - T_T%@\n%@\n %@", path, params, error);
        }
    }];
}
@end
